import os
import argparse
import urllib.parse
from git import Repo


def git_download_main(git_url:str, target):
    if target == "":
        target = git_url[git_url.rstrip("/").rfind("/")+1:]
        target.replace(".git", "")
    assert "/" not in target, target
    
    if os.path.exists(target):
        print(f"Directory {target} already exists. Abort.")
        return
    
    os.system(f"git clone --depth 1 {git_url} {target}")
    if not os.path.exists(target):
        print("Clone Failed. Abort.")
        return
        
    repo = Repo(target)
    hash = repo.head.commit.hexsha[:6]
    
    if os.path.exists(f"{target}_{hash}"):
        print(f"Directory {target}_{hash} already exists. Abort.")

    os.system(f"rm -rf {target}/.git")
    os.system(f"mv {target} {target}_{hash}")

def git_download_branch(git_repo, target, branch):
    assert "/" not in branch
    
    # git clone --depth 1  --branch <branch> url
    if target == "":
        target = git_repo[git_repo.rstrip("/").rfind("/")+1:]
        target.replace(".git", "")
    assert "/" not in target, target
    
    if os.path.exists(target):
        print(f"Directory {target} already exists. Abort.")
        return
    
    os.system(f"git clone --depth 1 --branch {branch} {git_repo} {target}")
    if not os.path.exists(target):
        print("Clone Failed. Abort.")
        return
        
    repo = Repo(target)
    hash = repo.head.commit.hexsha[:6]
    
    if os.path.exists(f"{target}_{hash}"):
        print(f"Directory {target}_{hash} already exists. Abort.")

    os.system(f"rm -rf {target}/.git")
    os.system(f"mv {target} {target}_{hash}")

def git_download_folder(git_url, target):
    git_url = git_url.rstrip("/")
    if target == "":
        target = git_url[git_url.rfind("/")+1:]
    assert "/" not in target, target
    cmd = f"gh-folder-download --url {git_url} --output {target}"
    os.system(cmd)

def git_download_file(git_url, target):
    if target == "":
        target = git_url[git_url.rstrip("/").rfind("/")+1:]
    assert "/" not in target, target
    
    ghsite = "github.com/"
    sep = git_url.find(ghsite) + len(ghsite)
    raw_url = "https://raw.githubusercontent.com/" + git_url[sep:]
    # raw_url = "https://raw.gitmirror.com/" + git_url[sep:]
    # print(raw_url)
    os.system(f"wget {raw_url} -O {target}")
    
def main():
    argp = argparse.ArgumentParser()
    argp.add_argument("git_url")
    argp.add_argument("target", nargs="?", default="")
    args = argp.parse_args()
    
    git_url = args.git_url
    target = args.target
    
    if "/tree/" in git_url:
        git_repo, branch = git_url.split("/tree/")
        branch = branch.strip("/")
        if "/" in branch:
            git_download_folder(git_url, target)
        else:
            git_download_branch(git_repo, target, branch)
    elif "/blob/" in git_url:
        git_download_file(git_url, target)
    else:
        git_download_main(git_url, target)
    
if __name__ == "__main__":
    main()
